<template>
  <div>
    <el-row :gutter="10"
      style="padding: 10px">
      <el-card class="newGroup">
        <el-col :span="6"
          style="overflow-y: auto; height: 800px;">
          <el-tree :data="data"
            :default-expand-all="isShowExand"
            :props="defaultProps"
            ref="tree"
            node-key="label"
            show-checkbox=""
            @check-change="handleCheckChange"></el-tree>
        </el-col>
        <el-col :span="18"
          style="padding-bottom: 40px">
          <h2 style="text-align: left">人群同时满足下列规则</h2>
          <el-card v-for="card in cards"
            :key="card.title"
            style="margin-bottom: 20px">
            <h3 style="text-align: left">{{card.title}}</h3>
            <p style="text-align: left">
              <el-radio-group v-model="card.value"
                v-if="card.tag_type === 1">
                <el-radio v-for="tag in card.tags"
                  :key="tag.tag_id"
                  :label="tag.tag_id"
                  style="padding: 5px 0">
                  {{tag.tag_name}}</el-radio>
              </el-radio-group>
              <el-radio-group v-model="radio"
                v-if="card.tag_type === 2">
                <el-radio :label="3">区间</el-radio>
                <el-radio :label="6">大于</el-radio>
                <el-radio :label="9">小于</el-radio>
              </el-radio-group>
            </p>
            <el-row v-if="card.tag_type === 2">
              <el-col :span="6">
                <el-input type="number"
                  style="width: 100%"
                  v-model="card.value1"
                  :disabled="radio === 9"></el-input>
              </el-col>
              <el-col :span="6"
                style="font-size: 24px; font-weight: bolder">————</el-col>
              <el-col :span="6">
                <el-input type="number"
                  style="width: 100%"
                  v-model="card.value2"
                  :disabled="radio === 6"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-row>
          </el-card>
          <el-form :model="addForm"
            :rules="addFormRules"
            ref="addFormRef"
            label-width="70px">
            <el-form-item label="标签关系"
              prop="relationship">
              <el-select v-model="addForm.relationship"
                placeholder="请选择"
                value="and"
                style="float: left;width: 400px">
                <el-option label="且"
                  value="and">
                </el-option>
                <el-option label="或"
                  value="or">
                </el-option>
              </el-select>
            </el-form-item>
            <el-row>
              <el-col :span="8">
                <el-button type="primary"
                  @click="countGroup"
                  style="float: left">计算人群数量</el-button>
              </el-col>
              <el-col :span="16">
                <p style="margin: 0;text-align: left; height: 40px; line-height: 40px">{{total}} 人</p>
              </el-col>
            </el-row>
            <el-form-item label="人群名称"
              prop="group_name"
              style="padding: 20px 0">
              <el-input v-model="addForm.group_name"
                style="width: 400px; float: left"></el-input>
            </el-form-item>
            <el-form-item label="是否下线"
              prop="is_online"
              style="padding: 20px 0">
              <el-select v-model="addForm.is_online"
                placeholder="请选择"
                style="width: 400px; float: left">
                <el-option label="上线"
                  value="上线">
                </el-option>
                <el-option label="下线"
                  value="下线">
                </el-option>
              </el-select>
            </el-form-item>
            <el-button type="primary"
              style="float: left; margin-left: 180px;"
              @click="handleCommit()">保存</el-button>
            <el-button type="primary"
              style="float: left; margin-left: 10px;"
              @click="goBack()">取消</el-button>
          </el-form>
        </el-col>
      </el-card>
    </el-row>
  </div>
</template>

<script>
export default {
  data () {
    return {
      data: [],
      defaultProps: {
        // children: 'children',
        // label: 'label'
      },
      radio: 3,
      cards: [],
      addForm: {
        group_id: '',
        relationship: '',
        group_name: '',
        is_online: '',
        rules: '',
        reach_count: ''
      },
      editForm: {},
      addFormRules: {},
      total: 0,
      operation: 0,
      tagList: [],
      isShowExand: true,
      Exgroup_id: null
    }
  },
  created () {
    // console.log(this.$route.params)
    this.getTags()
    if (this.$route.params.group_name) window.sessionStorage.setItem('group_id', this.$route.params.group_id)
    if (window.sessionStorage.getItem('group_id')) {
      this.getEditForm(window.sessionStorage.getItem('group_id'))
      this.operation = 1
      this.isShowExand = true
    } else {
      this.isShowExand = false
    }
  },
  methods: {
    async getEditForm (group_id) {
      const {
        data: res
      } = await this.$http.post('http://127.0.0.1:8080/userprofile-platform/v1/UserGroup/searchUsergroupById', {}, {
        params: {
          group_id: group_id
        }
      })
      console.log(res);
      this.editForm = res.data.list[0]
      const checkedNode = []
      // console.log(this.editForm.rules.replace(/\\/g, ''))
      const rules = JSON.parse(this.editForm.rules.replace(/\\/g, ''))
      this.addForm.relationship = rules.relationship
      rules.ruledetails.forEach((item) => {


        this.tagList.forEach((etem) => {
          if (etem.tag_id === item.key) {
            checkedNode.push(etem.level_2_name)
            const card = {}
            if (item.value.indexOf("[") == -1) {
              const tags = []
              this.tagList.forEach((ctem) => {
                if (etem.level_2_name === ctem.level_2_name) {
                  tags.push({
                    tag_id: ctem.tag_id,
                    tag_name: ctem.tag_name
                  })
                }
              })
              card.tag_type = 1
              card.tags = tags
              card.title = etem.level_2_name
              card.value = etem.tag_id
            } else if (item.value.indexOf("[") != -1) {
              const arr = item.value.split(',')
              const reg = /\d/;
              const min = arr[0].match(reg)
              const max = arr[1].match(reg)
              if (min && max) this.radio = 3
              else if (min && !max) this.radio = 6
              else this.radio = 9
              card.tag_type = 2
              card.tag_id = etem.tag_id
              card.title = etem.tag_name
              card.value1 = min ? min[0] : null
              card.value2 = max ? max[0] : null
            } else {
              alert('参数错误')
            }
            this.cards.push(card)
          }
        })
      })
      this.$refs.tree.setCheckedKeys(checkedNode)







      this.total = this.editForm.reach_count
      this.addForm.group_id = this.editForm.group_id
      this.addForm.group_name = this.editForm.group_name
      this.addForm.is_online = this.editForm.is_online

    },
    async getTags () {
      const {
        data: res
      } = await this.$http.post('http://127.0.0.1:8080/userprofile-platform/v1/UserGroup/usergroupAnalysisList')
      console.log(res);
      var that = this
      this.tagList = res.info.list
      res.info.list.forEach((item) => {
        let isAdd1 = false
        let isAdd2 = false
        that.data.forEach((etem) => {
          if (etem.label === item.level_1_name) {
            isAdd1 = true
            etem.children.forEach((dtem) => {
              if (dtem.label === item.level_2_name) {
                isAdd2 = true
                dtem.tags.push({
                  tag_name: item.tag_name,
                  tag_id: item.tag_id
                })
              }
            })
            if (!isAdd2) {
              etem.children.push({
                label: item.level_2_name,
                tags: [{
                  tag_name: item.tag_name,
                  tag_id: item.tag_id
                }]
              })
            }
          }
        })
        if (!isAdd1) {
          that.data.push({
            label: item.level_1_name,
            children: [{
              label: item.level_2_name,
              tags: [{
                tag_name: item.tag_name,
                tag_id: item.tag_id
              }]
            }]
          })
        }
      })
    },
    handleCheckChange (dataChecked, checked, indeterminate) {
      if (dataChecked.children) {
        dataChecked.children.forEach((data) => {
          if (checked && !indeterminate) {
            let isExit = false
            this.cards.forEach((item) => {
              if (item.title === data.label) isExit = true
            })
            if (!isExit) {
              const card = {}
              if (data.tags.length > 1) {
                card.tag_type = 1
                card.tags = data.tags
                card.title = data.label
                card.value = ''
              } else if (data.tags.length === 1) {
                card.tag_type = 2
                card.tag_id = data.tags[0].tag_id
                card.title = data.label
                card.value1 = ''
                card.value2 = ''
              } else {
                alert('参数错误')
              }
              this.cards.push(card)
            }
          } else if (!checked && !indeterminate) {
            for (var i = 0; i < this.cards.length; i++) {
              if (this.cards[i].title === data.label) {
                this.cards.splice(i, 1);
              }
            }
          } else console.log(data, checked, indeterminate);
        })
      } else {
        const data = dataChecked
        if (checked && !indeterminate) {
          let isExit = false
          this.cards.forEach((item) => {
            if (item.title === data.label) isExit = true
          })
          if (!isExit) {
            const card = {}
            if (data.tags.length > 1) {
              card.tag_type = 1
              card.tags = data.tags
              card.title = data.label
              card.value = ''
            } else if (data.tags.length === 1) {
              card.tag_type = 2
              card.tag_id = data.tags[0].tag_id
              card.title = data.label
              card.value1 = ''
              card.value2 = ''
            } else {
              alert('参数错误')
            }
            this.cards.push(card)
          }
        } else if (!checked && !indeterminate) {
          for (var i = 0; i < this.cards.length; i++) {
            if (this.cards[i].title === data.label) {
              this.cards.splice(i, 1);
            }
          }
        } else console.log(data, checked, indeterminate);
      }

    },
    async countGroup () {
      const data = {
        ruleinfo: '{\"relationship\":\"' + this.addForm.relationship + '\",\"ruledetails\":[',
        issave: "1"
      }
      this.cards.forEach((item) => {
        if (item.tag_type === 1) {
          data.ruleinfo += '{\"key\":\"' + item.value + '\",\"value\":\"\"},'
        } else {
          data.ruleinfo += '{\"key\":\"' + item.tag_id + '\",\n' +
            '\"value\":\"[' + item.value1 + ',' + item.value2 + ']\"},'
        }
      })
      if (data.ruleinfo[data.ruleinfo.length - 1] == ',') {
        data.ruleinfo = data.ruleinfo.substring(0, data.ruleinfo.length - 1)
      }
      data.ruleinfo += ']}'
      this.addForm.rules = data.ruleinfo
      const {
        data: res
      } = await this.$http.post('http://127.0.0.1:8080/userprofile-platform/v1/UserGroup/usergroupCalculate', data)
      this.total = res.data.total
      this.addForm.reach_count = res.data.total
    },
    async handleCommit () {
      if (!this.operation) {
        const {
          data: res
        } = await this.$http.post('http://127.0.0.1:8080/userprofile-platform/v1/UserGroup/addUsergroup', this.addForm)
        if (res.code === '100') {
          this.$message.success('添加成功！')
          await this.$router.push({
            name: 'GroupList'
          })
        }
      } else {
        const {
          data: res
        } = await this.$http.post('http://127.0.0.1:8080/userprofile-platform/v1/UserGroup/updateUsergroup', this.addForm)
        if (res.code === '100') {
          this.$message.success('修改成功！')
          await this.$router.push({
            name: 'GroupList'
          })
        }
      }
    },
    async goBack () {
      await this.$router.push({
        name: 'GroupList'
      })
    }
  },
  watch: {
    Exgroup_id () {
      this.$nextTick(() => {
        // this.isShowExand = true
      })
    }
  }
}

</script>

<style scoped>
</style>
